package com.lanou.fooddemo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.lanou.fooddemo.R;
import com.lanou.fooddemo.adapter.SameCityListAdapter;
import com.lanou.fooddemo.adapter.TopicDetailsAdapter;
import com.lanou.fooddemo.bean.DataBean;
import com.lanou.fooddemo.bean.DetailBean;
import com.lanou.fooddemo.external.material_loading_progress_bar.CircleProgressBar;
import com.lanou.fooddemo.external.smart_image_view.SmartImageView;
import com.lanou.fooddemo.external.swipe_refresh_loading_layout.SwipeRefreshLoadingLayout;
import com.lanou.fooddemo.util.CommonUtil;
import com.lanou.fooddemo.util.NetUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

/**
 * Created by dlios on 15-8-10.
 */
//话题详情页
public class TopicDetailsActivity extends Activity {

    private static final String LOG_TAG = "TopicDetailsActivity";

    /**
     * 传递给详细信息界面的Extra数据key
     */
    public static final String INFORMATION_KEY = "topicDetails";

    /**
     * 设置读取中dialog显示类型值
     */
    private final int TYPE_DIALOG_SHOW = 1;
    /**
     * 首次拉取数据的Message的类型值
     */
    private final int TYPE_GET_DATA = 2;
    /**
     * 非首次拉取数据的Message的类型值
     */
    private final int TYPE_GET_NEXT_DATA = 3;

    private List<DataBean> dataBeans;
    private TopicDetailsAdapter adapter;
    private View.OnClickListener clickListener;

    /**
     * 定义list刷新进度条颜色
     */
    private int[] listColor = {android.R.color.holo_red_light, android.R.color.white,
            android.R.color.holo_red_light, android.R.color.holo_red_light};
    private android.os.Handler handler;

    private TextView backTextView;
    /**
     * 数据ListView
     */
    private ListView listView;
    /**
     * 刷新布局
     */
    private SwipeRefreshLoadingLayout swipeRefreshLoadingLayout;
    /**
     * 读取中Dialog
     */
    private CircleProgressBar circleProgressBar;
    private SmartImageView topicDetails_header_picture;
    private TextView topicDetails_header_theme;
    private TextView topicDetails_header_themeNumber;
    private SmartImageView topicDetails_header_headPortrait;
    private TextView topicDetails_header_userName;
    private TextView topicDetails_header_userSign;
    private TextView topicDetails_header_describe;


    //   @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        //通过LayoutInflater从layout布局中获得布局view
//        View view = inflater.inflate(R.layout.fragment_same_city, null);
//        //初始化控件
//        initView(view);
//        //首次进入获取数据
//        getSameCityData(TYPE_GET_DATA);
//
//        return view;
//    }

    private String api;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.topic_details_listview);

        initView();
        //首次进入获取数据
        getSameCityData(TYPE_GET_DATA);

    }


    /**
     * 控件初始化方法
     */
    private void initView() {
        api = getIntent().getStringExtra(INFORMATION_KEY);
        Log.i("liuyan", "api = " + api);
        listView = (ListView) findViewById(R.id.topic_details_listview);
        backTextView = (TextView) findViewById(R.id.topicReturn);
        View view = LayoutInflater.from(this).inflate(R.layout.topic_details_header, null);
//        DataBean dataBean = null;
//       DataBean userCardBean = dataBeans.get(1);
//        DataBean ContentCardBean = dataBeans.get(2);
//        if (CommonUtil.isListNotNull(dataBeans)) {
//            dataBean = dataBeans.get(0);
//
//        }
        //实例化点击监听类
        clickListener = new InformationOnClickListener();

        //设置返回按钮点击监听
        backTextView.setOnClickListener(clickListener);


        //解析EventCard
        topicDetails_header_picture = (SmartImageView) view.findViewById(R.id.topicDetails_header_picture);
        topicDetails_header_theme = (TextView) view.findViewById(R.id.topicDetails_header_Theme);
        topicDetails_header_themeNumber = (TextView) view.findViewById(R.id.topicDetails_header_ThemeNumber);
//        topicDetails_header_picture.setImageUrl(dataBean.getPic().getUrl());
//        topicDetails_header_Theme.setText(dataBean.getTitle());
//        topicDetails_header_ThemeNumber.setText(dataBean.getDesc());

        //解析UserCard
        topicDetails_header_headPortrait = (SmartImageView) view.findViewById(R.id.topicDetails_header_headPortrait);
        topicDetails_header_userName = (TextView) view.findViewById(R.id.topicDetails_header_UserName);
        topicDetails_header_userSign = (TextView) view.findViewById(R.id.topicDetails_header_UserSign);
//        topicDetails_header_UserName.setText(userCardBean.getTitle());
//        topicDetails_header_UserSign.setText(userCardBean.getDesc());
//        topicDetails_header_headPortrait.setImageUrl(userCardBean.getUser().getAvatar());

        //解析contentcard
        topicDetails_header_describe = (TextView) view.findViewById(R.id.topicDetails_header_describe);
//        topicDetails_header_describe.setText(ContentCardBean.getContent());
//        TextView textview = (TextView) view.findViewById(R.id.RecommendeTopicsRightImageView);
//
        listView.addHeaderView(view);
        swipeRefreshLoadingLayout =
                (SwipeRefreshLoadingLayout) findViewById(R.id.topicDetails_SwipeLayout);
        circleProgressBar = (CircleProgressBar) findViewById(R.id.sameCityProgressBar);


        //设置读取中dialog显示
        circleProgressBar.setVisibility(View.VISIBLE);
        //初始化列表数据
        dataBeans = new ArrayList<DataBean>();
        //初始化列表适配器
        adapter = new TopicDetailsAdapter(this, dataBeans);
        //为listView绑定适配器
        listView.setAdapter(adapter);
        //为刷新布局添加进度条颜色
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        //注册下拉刷新
        swipeRefreshLoadingLayout.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取首次拉取数据
                getSameCityData(TYPE_GET_DATA);
            }
        });
        //注册上拉加载更多
        swipeRefreshLoadingLayout.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                //加载更多数据
                getSameCityData(TYPE_GET_NEXT_DATA);
            }
        });
//        //注册listView按下监听
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                //创建跳转详细信息界面的Activity的Intent
//                Intent intent = new Intent(getActivity(), SameCityInformationActivity.class);
//                //获取列表相应点击位置的跳转信息
//                DetailBean detailBean = dataBeans.get(position).getDetail();
//                //将需要跳转的url携带信息传递到详细信息界面
//                intent.putExtra(INFORMATION_KEY, detailBean.getApi());
//                //跳转到详细信息界面
//                startActivity(intent);
//            }
//        });
        //实例化Handler
        handler = new android.os.Handler(new android.os.Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case TYPE_DIALOG_SHOW:
                        //显示读取中dialog
                        circleProgressBar.setVisibility(View.VISIBLE);
                        break;
                    //处理首次进入和下拉刷新的数据更新
                    case TYPE_GET_DATA:
                        //清空dataBeans的List
                        dataBeans.clear();


                        //变量接收消息对象附带值
                        List<DataBean> firstDataBeans = (List<DataBean>) msg.obj;
                        //获取List中第一个话题栏DataBean
                        DataBean firstDataBean = firstDataBeans.get(0);


                        //去掉第一个话题栏Bean
                        //firstDataBeans.remove(0);
                        //将msg中的数据全部填充到dataBeans
                        dataBeans.addAll(firstDataBeans);
                        //取消刷新状态
                        swipeRefreshLoadingLayout.setRefreshing(false);
                        //设置读取中进度条不显示
                        circleProgressBar.setVisibility(View.INVISIBLE);

                        DataBean dataBean = null;
                        DataBean userCardBean = dataBeans.get(1);
                        DataBean ContentCardBean = dataBeans.get(2);
                        if (CommonUtil.isListNotNull(dataBeans)) {
                            dataBean = dataBeans.get(0);

                            topicDetails_header_picture.setImageUrl(dataBean.getPic().getUrl());
                            topicDetails_header_theme.setText(dataBean.getTitle());
                            topicDetails_header_themeNumber.setText(dataBean.getDesc());
                            topicDetails_header_userName.setText(userCardBean.getTitle());
                            topicDetails_header_userSign.setText(userCardBean.getDesc());
                            topicDetails_header_headPortrait.setImageUrl(userCardBean.getUser().getAvatar());
                            topicDetails_header_describe.setText(ContentCardBean.getContent());

                        }
                        break;
                    //处理加载更多的数据更新
                    case TYPE_GET_NEXT_DATA:
                        //将msg中的数据全部填充到dataBeans
                        dataBeans.addAll((List<DataBean>) msg.obj);
                        //取消加载更多状态
                        swipeRefreshLoadingLayout.setLoading(false);
                        //设置读取中进度条不显示
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                }
                //通知适配器数据改变，更新视图
                adapter.notifyDataSetChanged();
                return true;
            }
        });
    }

    /**
     * 获取同城数据
     *
     * @param type 拉取类型，是刷新或首次拉取还是非首次拉取
     * @param-url 获取数据的url
     */
    private void getSameCityData(int type) {
        //实例化自定义Runable接口类SameCityRunable
        SameCityRunable sameCityRunable = new SameCityRunable(type);
        //将Runable实例类放入Thread构造方法,实例化线程
        Thread thread = new Thread(sameCityRunable);
        //开启线程
        thread.start();
    }

    private class SameCityRunable implements Runnable {

        /**
         * 读取中进度条显示消息
         */
        private Message msgDialogShow;
        /**
         * 数据传递消息
         */
        private Message msgData;
        /**
         * 首次拉取或非首次拉取类型
         */
        private int type;
        List<DataBean> runableDataBeanList = null;

        public SameCityRunable(int t) {
            type = t;
        }

        @Override
        public void run() {
            //从handler中获取消息赋给进度条显示消息
            msgDialogShow = handler.obtainMessage();
            //设置消息类型what值
            msgDialogShow.what = TYPE_DIALOG_SHOW;
            //发送进度条显示消息
            handler.sendMessage(msgDialogShow);
            //判断数据拉取类型，从不同接口拉取数据
            if (TYPE_GET_DATA == type) {
                runableDataBeanList = NetUtil.getDataBeanListDataForTopicDetailsList(api);
            } else if (TYPE_GET_NEXT_DATA == type) {
                runableDataBeanList = NetUtil.getDataBeanListDataForTopicDetailsListForNext(api);
            }

            if (CommonUtil.isListNotNull(runableDataBeanList)) {
                //从handler获取消息
                msgData = handler.obtainMessage();
                //设置消息what值
                msgData.what = type;
                //设置消息obj内容值
                msgData.obj = runableDataBeanList;
                Log.d("TAGG", "runableDataBeanList 的大小为:" + runableDataBeanList.size());
//                Log.d("TAGG","runableDataBeanList 的大小为:"+runableDataBeanList.get(0).getPic().getUrl());
//                Log.d("TAGG","runableDataBeanList 的大小为:"+runableDataBeanList.get(1).getUser().getAvatar());
                Log.d("TAGG", "runableDataBeanList 的大小为:" + runableDataBeanList.get(2).getContent());
                //发送消息给handler
                handler.sendMessage(msgData);
            }
        }
    }
    private class InformationOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.topicReturn:
                    //销毁当前Activity
                    finish();
                    break;
            }

        }
    }
}
